package com.itheima.utils;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 *      传统的 JDBC 代码重复度太高
 *          -- 注册驱动的代码要抽取
 *          -- 抽取一个方法连接对象
 *          -- 抽取一个方法释放资源
 */
public class JDBCUtils {

    /**
     * 只有静态的才能被静态代码块访问
     */
    private static String className ;
    private static String url ;
    private static String username ;
    private static String password ;

    /**
     * 文件的读取 只用执行一次
     */
    static {
        ClassLoader classLoader = JDBCUtils.class.getClassLoader();
        String path = classLoader.getResource("jdbc.properties").getPath();

        //url切换编码
        try {
            path = URLDecoder.decode(path, "UTF-8") ;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println(path);

        Properties properties = new Properties() ;
        try {
            properties.load(new FileReader(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //获取信息
         className = properties.getProperty("className") ;
         url = properties.getProperty("url") ;
         username = properties.getProperty("username") ;
         password = properties.getProperty("password") ;

    }

    /**
     * 获取连接          用配置文件解决传参问题
     * @return
     */
    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        //创建连接对象
        Class.forName(className) ;
        Connection connection = DriverManager.getConnection(url, username, password);

        return connection ;
    }

    /**
     * 释放资源
     * @param statement
     * @param connection
     */
    public static void close (Statement statement , Connection connection) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (connection != null) {
                connection.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void close (Statement statement , Connection connection , ResultSet result) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (connection != null) {
                connection.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (result != null) {
                result.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
